# coding: utf-8

from copy import deepcopy

from flask import request

from dbproxy.dbproxy import *
from login.LoginFunc import *
from result import *
import UploadSurvey as US

log = getFileLog()

DB_Proxy = DBProxy(db=mongo.db)


class MonitorSurvey(object):
    """
    问卷监控模块
    """

    _redis = RedisOper.RedisOper

    def __init__(self):
        super(MonitorSurvey, self).__init__()

    def add_monitor_task(self, code, channel, type=0, emails=None, monitor_field=False, have_attach=0):
        """
        监控问卷使用情况
        :param code: 
        :param channel: 
        :param type: 
        :param emails: 
        :param monitor_field: 
        :param have_attach: 
        :return: 
        """
        if self._redis.get(code) is not None:
            return False
        data = {
            'code': code,
            'channel': channel,
            'type': type,
            'emails': emails,
            'monitor_field': monitor_field,
            'have_attach': have_attach,
            'active': 1
        }
        #
        # 监控列表
        self._redis.rpush(task_key, json.dumps(data, sort_keys=True))
        self._redis.set(code, json.dumps(data, sort_keys=True))
        return True

    def get_monitor_task(self):
        data = self._redis.lpop(task_key)
        try:
            data = data.decode()
            data = json.loads(data)
            return data
        except Exception as e:
            log.error(e)
            return None

    def delete_monitor(self, code):
        """
        根据code删除监控任务
        :param code: 
        :return: 
        """
        data = self._redis.get(code)
        self._redis.lrem(task_key, data)
        self._redis.delete(code)

    def clear_all_task(self):
        log.info('删除所有监控任务')
        self._redis.delete(task_key)

    def get_survey_users_count(self, compnay_list):
        '''
        根据公司名获取问卷当前参与人数: 去重
        :param compnay_list:  ['1','x','2']
        :return: 
        '''
        db = mongo.db
        ret = deepcopy(g_ret)
        #
        # 从response_collection获取每个公司每份问卷的参与用户数
        survey_types = {}
        survey_types[0] = '人格标准问卷模板'
        survey_types[1] = '人格特征问卷模板'
        survey_types[2] = '用户问卷'
        for company in compnay_list['data']:
            # log.debug("公司: %s"%(company))
            #
            # 取出该公司下的所有问卷
            ret_company = db['company_collection'].find({'company_name': company})
            for companyitem in ret_company:
                companyid = companyitem.get('guid')
            surveys = db['surveys_collection'].find({'$or': [{'company_id': company}, {'company_id': companyid}]})
            for survey in surveys:
                data = {}
                # data['surveys'] = []
                #
                # 遍历每一张问卷，获取统计数据
                survey_data = {}
                code = survey.get('code')
                title = survey.get('title')
                type = survey.get('survey_type')
                emails = survey.get('monitor_mail')  # list类型

                channel = code + '_channel'

                resps = db['responses_collection'].find({'code': code, 'response.channel': channel})
                user_pv = resps.count()
                user_uv = len(resps.distinct('response.wxid'))
                del survey['_id']
                data = survey
                # data['company_id'] = company
                data['code'] = code
                data['channel'] = channel
                data['title'] = title
                data['type'] = survey_types[type]
                #
                # Xiaodong. Yang
                # 鉴于目前获取用户唯一标识难度较大，uv值存在较大误差，
                # 所以，将uv,pv统一设为pv， 减少前端工作量
                data['uv'] = user_pv
                data['pv'] = user_pv
                data['emails'] = emails

                ret['data'].append(data)
            ret['code'] = 200
            ret['total_count'] = len(ret['data'])
        return ret


@app.route('/monitor/companys', methods=['GET', 'POST'])
@verify_token
def handle_monitor_companys():
    log.debug('get all monitor list')
    param = get_param(request)
    log.debug('获取公司信息')
    log.info(param)
    ms = MonitorSurvey()
    return json.dumps(ms.get_survey_users_count(param))


@app.route('/monitor/add', methods=['GET', 'POST'])
@verify_token
def handle_add_monitor():
    '''
    添加监控
    :return: 
    '''
    log.debug('开启监控')
    param = get_param(request)
    log.debug(param)

    ms = MonitorSurvey()

    code = param.get('code')
    if code is None:
        code = ''
    channel = code + '_channel'
    emails = param.get('emails')
    ems = ''
    ret = deepcopy(g_ret)
    if emails is None or code is None:
        return json.dumps(ret)

    for em in emails:
        if len(ems) > 5:
            em += ','
        ems += em
    bret = ms.add_monitor_task(code=code, channel=channel, emails=ems)

    if bret:
        ret['code'] = 200
    else:
        ret['code'] = 400
    ret['msg'] = ''
    return json.dumps(ret)


@app.route('/monitor/del', methods=['GET', 'POST'])
@verify_token
def handle_del_monitor():
    log.debug('取消监控')
    param = get_param(request)
    code = param.get('code')

    ret = deepcopy(g_ret)
    if code is None:
        log.error('未指定问卷Code')
        return json.dumps(ret)

    ms = MonitorSurvey()
    ms.delete_monitor(code)

    ret['code'] = 200
    ret['msg'] = '成功'
    return json.dumps(ret)


@app.route('/monitor/export', methods=['GET', 'POST'])
@verify_token
def handler_export():
    params = get_param(request)
    #
    # 获取需要下载的问卷code
    code = params.get("code")
    token = params.get('token')
    LOG.debug('export %s' % code)
    _, user = RedisOper.RedisOper.get_userid_bytoken(token)
    print(user)
    LOG.debug('user: %s' % user)
    dest_excel = './static/%s.xlsx' % code
    US.export_resp(db=mongo.db, code=code, filename=dest_excel)
    LOG.debug('file saved')
    response = make_response(send_file(dest_excel))
    response.headers['Content-Disposition'] = 'attachment;filename=%s.xlsx' % (code)
    return response


@app.route('/question/export', methods=['GET', 'POST'])
@verify_token
def questions_export():
    params = get_param(request)
    questions = params.get("questions")
    code = '28Q_questions'
    dest_excel = './static/%s.xlsx' % code
    US.export_questions(db=mongo.db, questions=questions, filename=dest_excel)
    LOG.debug('question file saved')
    response = make_response(send_file(dest_excel))
    response.headers['Content-Disposition'] = 'attachment;filename=%s.xlsx' % (code)
    return response


@app.route('/surveys/export', methods=['GET', 'POST'])
@verify_token
def surveys_export():
    params = get_param(request)
    code = 'all_surveys'
    dest_excel = './static/%s.xlsx' % code
    US.surveys_resp(db=mongo.db,  filename=dest_excel)
    LOG.debug('surveys file saved')
    response = make_response(send_file(dest_excel))
    response.headers['Content-Disposition'] = 'attachment;filename=%s.xlsx' % (code)
    return response


if __name__ == '__main__':
    ms = MonitorSurvey()
    try:
        # param = {'token':111, 'data':['1','2']}
        # ms.get_survey_users_count(param)
        # ms.delete_monitor('canfu-hr')
        # ms.delete_monitor('rjkk')
        #
        ms.add_monitor_task(code='riskpreference', channel='xinhe',
                            emails='xiaodong.yang@unidt.com,xuan.feng@unidt.com,haoyu.chen@unidt.com,shuyu.jiang@unidt.com')
        # ms.add_monitor_task(code='rjkk', channel='rjkk',
        #                     emails='xiaodong.yang@unidt.com,fei.zhao@unidt.com')
    except Exception as e:
        print(e)
    # ms.delete_monitor('1')
    # data = ms.get_monitor_task()
    # while data is not None:
    #     print(data)
    #     data = ms.get_monitor_task()
